<template>
  <div id="manager-feedback">
    <el-container style="height: 100vh; border: 1px; overflow: hidden;">
      <el-header>
        <HeaderBar></HeaderBar>
      </el-header>
      <el-container style="flex: 1; display: flex;">
        <!-- 左侧栏 -->
        <el-aside :width="sidebarWidth" style="transition: width 0.3s ease; border-right: 1px solid #eee;">
          <Sidebar @sidebar-toggle="handleSidebarToggle"></Sidebar>
        </el-aside>
        <keep-alive>
          <!-- 主体内容区 -->
          <el-main :style="{
            marginLeft: '0',
            transition: 'margin-left 0.3s ease',
            width: `calc(100% - ${sidebarWidth})`,
          }" class="main-container">
            <el-container style="height: 100%; display: flex;">
              <!-- 左侧联系人列表 -->
              <div class="sidebar-content">
                <!-- 搜索框 -->
                <div class="search-section">
                  <div class="search-box">
                    <el-input v-model="searchKeyword" placeholder="搜索联系人" prefix-icon="el-icon-search"
                      class="search-input"></el-input>
                  </div>
                  <div class="search-divider"></div>
                </div>

                <!-- 联系人列表 -->
                <div class="contact-list">
                  <div v-for="contact in filteredContacts" :key="contact.userId" class="contact-item"
                    :class="{ 'active': contact.userId === currentContact.userId }" @click="selectContact(contact)">
                    <div class="contact-avatar">
                      <el-avatar :src="contact.avatar" size="small"></el-avatar>
                      <span v-if="contact.online" class="online-badge"></span>
                      <span v-if="!contact.online && contact.online !== undefined" class="offline-badge"></span>
                    </div>
                    <div class="contact-info-wrapper">
                      <div class="contact-info">
                        <div class="contact-name">
                          {{ contact.name }}
                          <el-badge v-show="contact.userId !== currentContact.userId" :value="contact.unreadCount || ''"
                            class="unread-badge" :class="{ 'hidden-badge': contact.unreadCount <= 0 }"></el-badge>
                        </div>
                        <div class="last-message">
                          <span>
                            {{ contact.lastMessage || '暂无消息' }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 右侧聊天内容区 -->
              <div class="chat-right-wrapper" style="flex: 1; display: flex; flex-direction: column;">
                <div style="height: 100%; padding: 5px; display: flex; flex-direction: column;">
                  <div v-if="currentContact && Object.keys(currentContact).length > 0" class="chat-container">
                    <!-- 聊天头部 -->
                    <div class="chat-header">
                      <div class="chat-header-content">
                        <el-avatar :src="currentContact.avatar" size="small"></el-avatar>
                        <div class="chat-header-info">
                          <div class="chat-title">
                            {{ currentContact.name }}
                            <span v-if="currentContact.online" class="online-text">在线</span>
                            <span v-if="!currentContact.online && currentContact.online !== undefined"
                              class="offline-text">离线</span>
                          </div>
                        </div>
                        <div class="chat-header-actions">
                          <el-dropdown>
                            <el-button icon="el-icon-more" circle size="mini"></el-button>
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item @click.native="openResumeDialog">查看资料</el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </div>
                      </div>
                    </div>

                    <!-- 消息列表 -->
                    <div class="message-list" ref="messageContainer">
                      <div v-for="(item, index) in messagesWithDates" :key="index">
                        <div v-if="item.type === 'date'" class="message-date-separator">
                          <span>{{ item.value }}</span>
                        </div>

                        <div v-else class="message-item" :class="{
                          'sent': item.data.fromUserId === currentManagerId,
                          'received': item.data.fromUserId !== currentManagerId
                        }">
                          <div class="message-avatar"
                            :class="{ 'sent-avatar': item.data.fromUserId === currentManagerId }">
                            <el-avatar
                              :src="item.data.fromUserId === currentManagerId ? myAvatar : currentContact.avatar"
                              size="small"></el-avatar>
                          </div>
                          <div class="message-content-wrapper">
                            <div class="message-bubble">
                              <div class="message-text">{{ item.data.message }}</div>
                              <div class="message-time">{{ formatTime(item.data.createdAt) }}</div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="system-message" v-if="messageList.length === 0">
                        开始与{{ currentContact.name }}聊天吧
                      </div>
                    </div>

                    <!-- 消息输入区 -->
                    <div class="message-input-area">
                      <div class="message-input-actions">
                        <el-button :icon="isInputVisible ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" circle size="mini"
                          class="toggle-input-btn" @click="toggleInputVisibility"></el-button>
                        <el-button icon="el-icon-picture" circle size="mini"></el-button>
                        <el-button icon="el-icon-folder-add" circle size="mini"></el-button>
                      </div>
                      <div ref="inputContainer" class="input-wrapper" :class="{ 'hidden': !isInputVisible }">
                        <el-input type="textarea" v-model="inputMessage" placeholder="输入消息..."
                          :autosize="{ minRows: 3, maxRows: 6 }" @keyup.enter.native="sendMessage" class="message-input"
                          resize="none"></el-input>
                        <div class="message-send-action">
                          <el-button icon="el-icon-paper-plane" type="primary" @click="sendMessage"
                            :disabled="!inputMessage.trim()" class="send-button">发送</el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="no-contact-selected">
                    <div class="empty-chat-container">
                      <div class="empty-icon">
                        <i class="el-icon-chat-dot-round"></i>
                      </div>
                      <div class="empty-title">选择一个联系人开始聊天</div>
                      <div class="empty-subtitle">与求职者和团队成员保持沟通</div>
                    </div>
                  </div>
                </div>
              </div>
            </el-container>
          </el-main>
        </keep-alive>
      </el-container>
    </el-container>
    <UserResumeDialog :visible.sync="resumeDialogVisible" :user="currentContact" class="userDialog"></UserResumeDialog>
  </div>
</template>

<script>
import Sidebar from "@/components/ManagerSidebar.vue";
import HeaderBar from "@/components/ManagerHeaderBar.vue";
import UserResumeDialog from "../components/ManaUserDialog.vue";
import { getManagers } from "@/util/manager_api/manager";
import { mapGetters } from 'vuex';

export default {
  activated() {
    this.checkWebSocketConnection();
  },
  components: {
    Sidebar,
    HeaderBar,
    UserResumeDialog
  },
  data() {
    return {
      searchKeyword: '',
      currentContact: {},
      currentManagerId: -1,
      myAvatar: '',
      contacts: [],
      filteredContacts: [],
      messageList: [],
      inputMessage: '',
      isSidebarCollapsed: false,
      isInputVisible: true,
      lastViewTimes: {},
      resumeDialogVisible: false
    };
  },
  mounted() {
    this.checkWebSocketConnection();
    this.setupWebSocketListeners();
    // 监听在线用户映射变化，实时更新状态
    this.$watch('onlineUsersMap', () => {
      this.updateAllContactsOnlineStatus();
    }, { deep: true });
    this.$watch('$route', () => this.checkWebSocketConnection());
  },
  computed: {
    ...mapGetters('manager', ['ws', 'onlineUsersMap', 'allChatRecords', 'userInfo']),
    sidebarWidth() {
      return this.isSidebarCollapsed ? '30px' : '200px';
    },
    messagesWithDates() {
      const result = [];
      let lastDate = null;

      this.messageList.forEach(msg => {
        const currentDate = new Date(msg.createdAt).toDateString();

        if (currentDate !== lastDate) {
          result.push({
            type: 'date',
            value: this.formatDate(new Date(msg.createdAt))
          });
          lastDate = currentDate;
        }

        result.push({
          type: 'message',
          data: msg
        });
      });

      return result;
    }
  },
  watch: {
    searchKeyword(val) {
      this.filteredContacts = this.contacts
        .filter(contact => contact.userId !== this.currentManagerId)
        .filter(contact => contact.name.toLowerCase().includes(val.toLowerCase()));
    },
    allChatRecords: {
      deep: true,
      handler() {
        this.contacts.forEach(contact => this.calcUnreadFromHistory(contact.userId));
      }
    },
    currentContact(val) {
      if (val && Object.keys(val).length > 0) {
        this.messageList = this.allChatRecords[val.userId] ? [...this.allChatRecords[val.userId]] : [];
        this.scrollToBottom();
        this.updateContactOnlineStatus(val.userId);
        this.lastViewTimes[val.userId] = new Date().toISOString();
        this.clearUnreadCount(val.userId);
        this.saveUnreadData();
      } else {
        this.messageList = [];
      }
    }
  },
  created() {
    this.initCurrentUserInfo();
    this.fetchManagers().then(() => {
      this.restoreUnreadData();
      this.updateAllContactsOnlineStatus();
    });
  },
  beforeDestroy() {
    if (this.ws) this.ws.off('ws-message');
  },
  methods: {
    checkWebSocketConnection() {
      if (!this.ws) {
        this.$store.dispatch('manager/initWebSocket').then(() => this.setupWebSocketListeners());
      } else if (!this.ws.isConnected && this.userInfo?.token) {
        this.ws.init(this.userInfo.token);
      }
    },
    setupWebSocketListeners() {
      if (!this.ws) return;
      
      this.ws.off('ws-message');
      this.ws.on('ws-message', (data) => {
        const rawData = this.ws.parseMessage(data);
        if (rawData) {
          // 处理文本消息
          if (rawData.messageType === 'TEXT') {
            this.handleNewMessage(rawData);
          }
          // 处理在线状态更新消息
          else if (rawData.messageType === 'ONLINE_USERS') {
            this.handleOnlineUsersUpdate(rawData);
          }
        }
      });
    },
    // 处理在线用户状态更新
    handleOnlineUsersUpdate(rawData) {
      if (typeof rawData.message === 'object' && rawData.message !== null) {
        // 更新Vuex中的在线用户映射
        this.$store.commit('manager/SET_ONLINE_USERS', rawData.message);
        // 刷新所有联系人的在线状态
        this.updateAllContactsOnlineStatus();
      }
    },
    selectContact(contact) {
      if (this.currentContact.userId) {
        this.lastViewTimes[this.currentContact.userId] = new Date().toISOString();
        this.saveUnreadData();
      }

      this.currentContact = { ...contact };
      this.messageList = this.allChatRecords[contact.userId] ? [...this.allChatRecords[contact.userId]] : [];

      // 记录当前时间为最后查看时间
      const viewTime = new Date().toISOString();
      this.lastViewTimes[contact.userId] = viewTime;

      // 标记该联系人的所有消息为已读
      if (this.allChatRecords[contact.userId]) {
        this.allChatRecords[contact.userId].forEach(msg => {
          msg.localRead = true;
        });
        // 更新Vuex中的聊天记录
        this.$store.commit('manager/SET_CHAT_RECORDS', {
          contactUserId: contact.userId,
          records: [...this.allChatRecords[contact.userId]]
        });
      }

      this.clearUnreadCount(contact.userId);
      this.scrollToBottom();
      this.saveUnreadData();
    },
    async fetchManagers() {
      try {
        const response = await getManagers({
          page: 0,
          size: 0,
          content: this.searchKeyword || ''
        });
        this.contacts = response.data.data.respList.map(item => ({
          ...item,
          role: 'manager',
          unreadCount: 0,
          lastMessage: '',
          lastTime: null,
          online: false // 初始化为离线
        })).filter(contact => contact.userId !== this.currentManagerId);

        this.filteredContacts = [...this.contacts];
      } catch (error) {
        console.error('获取管理员列表失败:', error);
      }
    },
    initCurrentUserInfo() {
      if (this.userInfo) {
        try {
          this.currentManagerId = this.userInfo.userId;
          this.myAvatar = this.userInfo.avatar || '';
        } catch (e) {
          console.error('解析用户信息失败:', e);
          this.$message.error('用户信息错误，请重新登录');
        }
      } else {
        this.$message.warning('未检测到登录信息，请登录');
        this.$router.push('/login');
      }
    },
    calcUnreadFromHistory(contactUserId) {
      const messages = this.allChatRecords[contactUserId] || [];
      const lastViewTime = this.lastViewTimes[contactUserId];

      // 未读判断逻辑
      const unreadCount = messages.filter(msg => {
        if (msg.localRead) return false;
        if (msg.fromUserId === this.currentManagerId) return false;
        if (!msg.online) return true;
        if (!lastViewTime) return true;
        return new Date(msg.createdAt) > new Date(lastViewTime);
      }).length;

      const index = this.contacts.findIndex(c => c.userId === contactUserId);
      if (index !== -1) {
        this.$set(this.contacts[index], 'unreadCount', unreadCount);
        const lastMsg = messages[messages.length - 1];
        if (lastMsg) {
          this.$set(this.contacts[index], 'lastMessage', lastMsg.message);
          this.$set(this.contacts[index], 'lastTime', lastMsg.createdAt);
        }
        this.saveUnreadData();
      }
    },
    handleNewMessage(msg) {
      if (msg.toUserId !== this.currentManagerId) return;

      // 新消息默认标记为未读
      msg.localRead = false;

      if (!this.allChatRecords[msg.fromUserId]) {
        this.$store.commit('manager/SET_CHAT_RECORDS', { contactUserId: msg.fromUserId, records: [] });
      }
      this.$store.commit('manager/SET_CHAT_RECORDS', {
        contactUserId: msg.fromUserId,
        records: [...this.allChatRecords[msg.fromUserId], msg]
      });

      const isCurrentContact = this.currentContact?.userId === msg.fromUserId;

      if (!isCurrentContact) {
        this.updateUnreadCount(msg.fromUserId, 1);
      } else {
        // 当前聊天对象的消息自动标记为已读
        msg.localRead = true;
        this.messageList.push(msg);
        this.scrollToBottom();
        this.lastViewTimes[msg.fromUserId] = new Date().toISOString();
        this.saveUnreadData();
      }
    },
    restoreUnreadData() {
      const savedUnread = localStorage.getItem('managerUnreadData');
      if (savedUnread) {
        try {
          const unreadData = JSON.parse(savedUnread);
          this.contacts.forEach(contact => {
            const data = unreadData[contact.userId];
            if (data) {
              this.$set(contact, 'unreadCount', data.unreadCount);
              this.$set(contact, 'lastMessage', data.lastMessage);
              this.$set(contact, 'lastTime', data.lastTime);
              this.lastViewTimes[contact.userId] = data.lastViewTime || null;
            }
          });
        } catch (e) {
          console.error('恢复未读数据失败:', e);
          localStorage.removeItem('managerUnreadData');
        }
      }
    },
    sendMessage() {
      if (!this.inputMessage.trim() || !this.currentContact.userId) return;
      if (!this.ws || !this.ws.isConnected) {
        this.$message.error('WebSocket未连接,请稍后再试');
        return;
      }

      const now = new Date();
      const formattedTime = [
        now.getFullYear(),
        String(now.getMonth() + 1).padStart(2, '0'),
        String(now.getDate()).padStart(2, '0')
      ].join('-') + ' ' + [
        String(now.getHours()).padStart(2, '0'),
        String(now.getMinutes()).padStart(2, '0'),
        String(now.getSeconds()).padStart(2, '0')
      ].join(':');

      const message = {
        createdAt: formattedTime,
        fromRole: "manager",
        fromUserId: this.currentManagerId,
        message: this.inputMessage.trim(),
        messageType: "TEXT",
        toUserId: this.currentContact.userId,
        toRole: this.currentContact.role,
        // 根据onlineUsersMap判断接收方是否在线
        online: this.onlineUsersMap[this.currentContact.userId] !== undefined,
        localRead: true
      };

      this.messageList.push(message);
      this.$store.commit('manager/SET_CHAT_RECORDS', {
        contactUserId: this.currentContact.userId,
        records: [...this.allChatRecords[this.currentContact.userId], message]
      });
      this.inputMessage = "";
      this.scrollToBottom();

      this.ws.send(message).then(() => {
        this.lastViewTimes[this.currentContact.userId] = new Date().toISOString();
        this.saveUnreadData();
      }).catch(error => {
        console.error('消息发送失败:', error);
        this.$message.error('消息发送失败，请稍后再试');
      });
    },
    updateUnreadCount(contactId, count) {
      const index = this.contacts.findIndex(c => c.userId === contactId);
      if (index !== -1) {
        this.$set(this.contacts[index], 'unreadCount', this.contacts[index].unreadCount + count);
        this.filteredContacts = [...this.contacts];
        this.saveUnreadData();
      }
    },
    saveUnreadData() {
      const unreadData = {};
      this.contacts.forEach(contact => {
        unreadData[contact.userId] = {
          unreadCount: contact.unreadCount,
          lastMessage: contact.lastMessage,
          lastTime: contact.lastTime,
          lastViewTime: this.lastViewTimes[contact.userId]
        };
      });
      localStorage.setItem('managerUnreadData', JSON.stringify(unreadData));
    },
    clearUnreadCount(contactUserId) {
      const index = this.contacts.findIndex(c => c.userId === contactUserId);
      if (index !== -1) {
        this.$set(this.contacts[index], 'unreadCount', 0);
        this.filteredContacts = [...this.contacts];
        this.saveUnreadData();
      }
    },
    // 更新单个联系人在线状态
    updateContactOnlineStatus(contactUserId) {
      const index = this.contacts.findIndex(c => c.userId === contactUserId);
      if (index !== -1) {
        // 判断逻辑：如果onlineUsersMap中存在该userId的键，则为在线
        const isOnline = Object.prototype.hasOwnProperty.call(this.onlineUsersMap, contactUserId);
        this.$set(this.contacts[index], 'online', isOnline);
        this.filteredContacts = [...this.contacts];
      }
    },
    // 更新所有联系人在线状态
    updateAllContactsOnlineStatus() {
      this.contacts.forEach(contact => {
        this.updateContactOnlineStatus(contact.userId);
      });
    },
    openResumeDialog() {
      if (this.currentContact && Object.keys(this.currentContact).length > 0) {
        this.resumeDialogVisible = true;
        this.currentContact = {
          ...this.currentContact,
          stype : 'admin'
        }
      } else {
        this.$message.warning('请先选择一个联系人');
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) container.scrollTop = container.scrollHeight;
      });
    },
    formatTime(timeString) {
      const normalizedTime = timeString.replace('T', ' ').split('.')[0];
      const date = new Date(normalizedTime);
      return isNaN(date.getTime())
        ? '时间格式错误'
        : date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
    },
    formatDate(date) {
      if (typeof date === 'string') {
        date = new Date(date.replace('T', ' ').split('.')[0]);
      }
      return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
    },
    handleSidebarToggle(isCollapsed) {
      this.isSidebarCollapsed = isCollapsed;
    },
    toggleInputVisibility() {
      this.isInputVisible = !this.isInputVisible;
      if (!this.isInputVisible) this.inputMessage = '';
    }
  }
};
</script>
<style scoped>
@import url('./ManaFeedbackView.css');
</style>